package cn.darkhorse.admin.controller.workorder;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import cn.darkhorse.basic.domain.QmsProcessors;
import cn.darkhorse.basic.dto.BalanceRecordDTO;
import cn.darkhorse.basic.service.IQmsProcessorsService;
import cn.darkhorse.workorder.domain.*;
import cn.darkhorse.workorder.service.*;
import cn.darkhorse.workorder.vo.QmsWorkorderVO;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

/**
 * 流转单Controller
 *
 * @author ytq
 * @date 2024-07-19
 */

@RestController
@RequestMapping("/workorder/workorder")
public class QmsWorkorderController extends BaseController {

    @Resource
    private IQmsWorkorderService qmsWorkorderService;

    @Resource
    private IQmsWorkorderRecordService qmsWorkOrderRecordService;
    @Resource
    private IQmsWorkorderAuditService qmsWorkorderAuditService;

    @Resource
    private IQmsWorkorderHviService qmsWorkorderHviService;

    @Resource
    private IQmsWorkorderHviRecordService qmsWorkorderHviRecordService;

    @Resource
    private IQmsWorkorderSenseService qmsWorkorderSenseService;

    @Resource
    private IQmsWorkorderSampleBalanceService qmsWorkorderSampleBalanceService;

    @Resource
    private IQmsWorkorderSampleDeliveryService qmsWorkorderSampleDeliveryService;

    @Resource
    private IQmsProcessorsService qmsProcessorsService;

    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private IQmsWorkorderLogService qmsWorkorderLogService;

    /**
     * 查询流转单列表
     */
    @ApiOperation("列表")
    @GetMapping("/list")
    public TableDataInfo list(QmsWorkorder qmsWorkorder) {
        startPage();
        List<QmsWorkorder> list = qmsWorkorderService.selectQmsWorkorderList(qmsWorkorder);

        for (QmsWorkorder workorder : list) {
            workorder.setStatusName(
                    dictDataService.lambdaQuery().eq(SysDictData::getDictType,"order_status")
                            .eq(SysDictData::getDictValue,workorder.getStatus()).one().getDictLabel());
        }
        return getDataTable(list);
    }


    /**
     * 获取流转单详细信息
     */
    @ApiOperation("查看")
    @GetMapping(value = "/view")
    public AjaxResult view( Long id) {
        QmsWorkorder workorder = qmsWorkorderService.view(id);
//        翻译字典
        workorder.setStatusName(dictDataService.lambdaQuery()
                .eq(SysDictData::getDictType,"order_status")
                .eq(SysDictData::getDictValue,workorder.getStatus()).one().getDictLabel());
        return AjaxResult.success(workorder);
    }



    /**
     * 获取流转单详细信息
     */
    @ApiOperation("查看")
    @GetMapping(value = "/view-record")
    public AjaxResult viewRecord( Long id , Integer status) {
        QmsWorkorder qmsWorkorder = qmsWorkorderService.view(id);
        switch(status) {
                case 0:
                    QmsWorkorderSampleDelivery delivery = qmsWorkorder.getWorkorderSampleDelivery();
                    QmsWorkorderSampleBalance balance = qmsWorkorder.getWorkorderSampleBalance();
                    if (balance!=null){
                        delivery.setDeliveryTestRecord(balance.getDeliveryTestRecord());
                        delivery.setDeliveryTestRecords(JSONArray.parseArray(balance.getDeliveryTestRecord(), QmsWorkorderSampleBalanceRecord.class));
                        delivery.setDeliveryRemark(balance.getDeliveryRemark());
                        delivery.setDeliveryTestRecord(balance.getDeliveryTestRecord());
                        delivery.setDeliveryTesterSign(balance.getDeliveryTesterSign());
                        delivery.setDeliveryAuditorSign(balance.getDeliveryAuditorSign());
                        delivery.setDeliveryTestTime(balance.getDeliveryTestTime());
                        delivery.setDeliveryTesterCode(balance.getDeliveryTesterCode());
                        delivery.setDeliveryTesterModel(balance.getDeliveryTesterModel());
                        String username = SecurityUtils.getUsername();
                        if (username.equals(delivery.getDeliveryTester())){
                            delivery.setCanEditDelivery(1);
                        }else {
                            delivery.setCanEditDelivery(0);
                        }
                        if (username.equals(delivery.getDeliveryAuditor())){
                            delivery.setCanAuditDelivery(1);
                        }else {
                            delivery.setCanAuditDelivery(0);
                        }
                    }
                    return AjaxResult.success(delivery);
                case 1:
                    return AjaxResult.success(qmsWorkorder.getWorkorderSense());
                case 2:
                    QmsWorkorderSampleBalance balance2 = qmsWorkorder.getWorkorderSampleBalance();
                    if (balance2!=null){
                        balance2.setDeliveryTestRecords(JSONArray.parseArray(balance2.getDeliveryTestRecord(), QmsWorkorderSampleBalanceRecord.class));
                        balance2.setBeforeTestRecords(JSONArray.parseArray(balance2.getBeforeTestRecord(), QmsWorkorderSampleBalanceRecord.class));
                        balance2.setAfterTestRecords(JSONArray.parseArray(balance2.getAfterTestRecord(), QmsWorkorderSampleBalanceRecord.class));
                        // 判断是否有操作权限
                        String username = SecurityUtils.getUsername();
                        if (username.equals(balance2.getBeforeTester())){
                            balance2.setCanEditBefore(1);
                        }else {
                            balance2.setCanEditBefore(0);
                        }
                        if (username.equals(balance2.getAfterTester())){
                            balance2.setCanEditAfter(1);
                        }else {
                            balance2.setCanEditAfter(0);
                        }
                        if (username.equals(balance2.getBeforeAuditor())){
                            balance2.setCanAuditBefore(1);
                        }else {
                            balance2.setCanAuditBefore(0);
                        }
                        if (username.equals(balance2.getAfterAuditor())){
                            balance2.setCanAuditAfter(1);
                        }else {
                            balance2.setCanAuditAfter(0);
                        }
                    }

                    return AjaxResult.success(balance2);
                case 3:
                    QmsWorkorderHvi workorderHvi = qmsWorkorder.getWorkorderHvi();
                    if (workorderHvi!=null){
                        workorderHvi.setQmsWorkorderHviRecordList(qmsWorkorderHviRecordService.selectByHvi(workorderHvi));
                    }
                    return AjaxResult.success(workorderHvi);
                case 4:
                    return AjaxResult.success(qmsWorkorder.getWorkorderAudit());
        }
        return AjaxResult.success();
    }
    /**
     * 获取流转单详细信息
     */
    @ApiOperation("查看")
    @GetMapping(value = "/view-main")
    public AjaxResult viewMain( Long id) {
        QmsWorkorderVO workorderVO = qmsWorkorderService.viewMain(id);
        workorderVO.setStatusName(dictDataService.lambdaQuery()
                .eq(SysDictData::getDictType,"order_status")
                .eq(SysDictData::getDictValue,workorderVO.getStatus()).one().getDictLabel());
        return AjaxResult.success(workorderVO);
    }



    /**
     * 新增流转单
     */
    @ApiOperation("新增")
    @Log(title = "流转单", businessType = BusinessType.INSERT)
    @PostMapping(value = "save")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody QmsWorkorder qmsWorkorder)
    {
        if (qmsWorkorder.getOrderNumber()==null){
            qmsWorkorder.setOrderNumber(getOrderNumber().get("msg").toString());
        }
        QmsProcessors processors = qmsProcessorsService.getById(qmsWorkorder.getProcessorsId());
        if (processors!=null){
            qmsWorkorder.setProcessors(processors.getEnterpriseName());
        }
        return toAjax(qmsWorkorderService.saveQmsWorkorder(qmsWorkorder));
    }

    /**
     * 保存取送样品交接
     */
    @ApiOperation("保存取送样品交接")
    @Log(title = "取送样品交接", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveSampleDelivery")
    public AjaxResult saveSampleDelivery(@RequestBody QmsWorkorderSampleDelivery qmsSampleDelivery) {
        Long count = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, qmsSampleDelivery.getOrderNumber())
            .isNotNull(QmsWorkorderLog::getDelivery).count();
        if (count>0){
            return AjaxResult.warn("请勿重复提交");
        }

        if (qmsSampleDelivery.getType()==1){
            Date nowDate = DateUtils.getNowDate();
            qmsSampleDelivery.setOverTime(nowDate);
            qmsWorkorderLogService.lambdaUpdate().set(QmsWorkorderLog::getDelivery,nowDate)
                    .eq(QmsWorkorderLog::getOrderNumber,qmsSampleDelivery.getOrderNumber())
                    .update();
            nextStatus(qmsSampleDelivery.getOrderNumber());
        }
        QmsWorkorderSampleDelivery delivery = qmsWorkorderSampleDeliveryService.lambdaQuery()
                .eq(QmsWorkorderSampleDelivery::getOrderNumber, qmsSampleDelivery.getOrderNumber()).one();
        if (delivery!=null){
            qmsSampleDelivery.setId(delivery.getId());
        }
        if (qmsSampleDelivery.getDeliveryTestRecords()!=null){
            qmsSampleDelivery.setDeliveryTestRecord(JSONArray.copyOf(qmsSampleDelivery.getDeliveryTestRecords()).toJSONString());
        }

        return toAjax(qmsWorkorderSampleDeliveryService.saveQmsWorkorderSampleDelivery(qmsSampleDelivery));
    }

    /**
     * 保存感官检验
     */
    @ApiOperation("保存感官检验")
    @Log(title = "感官检验", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveSense")
    public AjaxResult saveSense(@RequestBody QmsWorkorderSense qmsWorkorderSense) {
        Long count = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, qmsWorkorderSense.getOrderNumber())
                .isNotNull(QmsWorkorderLog::getSense).count();

        if (count>0){
            return AjaxResult.warn("请勿重复提交");
        }

        if (qmsWorkorderSense.getType()==1){
            Date nowDate = DateUtils.getNowDate();
            qmsWorkorderSense.setOverTime(nowDate);
            qmsWorkorderLogService.lambdaUpdate().set(QmsWorkorderLog::getSense,nowDate)
                    .eq(QmsWorkorderLog::getOrderNumber,qmsWorkorderSense.getOrderNumber())
                    .update();
            nextStatus(qmsWorkorderSense.getOrderNumber());
        }
        QmsWorkorderSense sense = qmsWorkorderSenseService.lambdaQuery().eq(QmsWorkorderSense::getOrderNumber, qmsWorkorderSense.getOrderNumber()).one();
        if (sense!=null){
            qmsWorkorderSense.setId(sense.getId());
        }
        return toAjax(qmsWorkorderSenseService.saveQmsWorkorderSense(qmsWorkorderSense));
    }

    /**
     * 保存样品平衡
     */
    @ApiOperation("保存样品平衡")
    @Log(title = "样品平衡", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveSampleBalance")
    public AjaxResult saveSampleBalance(@RequestBody QmsWorkorderSampleBalance qmsWorkorderSampleBalance) {
        if (qmsWorkorderSampleBalance.getBeforeTestRecords()!=null){
            qmsWorkorderSampleBalance.setBeforeTestRecord(JSONArray.copyOf(qmsWorkorderSampleBalance.getBeforeTestRecords()).toJSONString());
        }
        if (qmsWorkorderSampleBalance.getAfterTestRecords()!=null){
            qmsWorkorderSampleBalance.setAfterTestRecord(JSONArray.copyOf(qmsWorkorderSampleBalance.getAfterTestRecords()).toJSONString());
        }
        Long count = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, qmsWorkorderSampleBalance.getOrderNumber())
                .isNotNull(QmsWorkorderLog::getBalance).count();
        if (count>0){
            return AjaxResult.warn("请勿重复提交");
        }

        if (qmsWorkorderSampleBalance.getType()==1){
            Date nowDate = DateUtils.getNowDate();
            qmsWorkorderSampleBalance.setOverTime(nowDate);
            qmsWorkorderLogService.lambdaUpdate().set(QmsWorkorderLog::getBalance,nowDate)
                    .eq(QmsWorkorderLog::getOrderNumber,qmsWorkorderSampleBalance.getOrderNumber())
                    .update();
            nextStatus(qmsWorkorderSampleBalance.getOrderNumber());
        }
        QmsWorkorderSampleBalance balance = qmsWorkorderSampleBalanceService.lambdaQuery().eq(QmsWorkorderSampleBalance::getOrderNumber, qmsWorkorderSampleBalance.getOrderNumber()).one();
        if (balance!=null){
            qmsWorkorderSampleBalance.setId(balance.getId());
        }


        return toAjax(qmsWorkorderSampleBalanceService.saveQmsWorkorderSampleBalance(qmsWorkorderSampleBalance));
    }

    /**
     * 保存hvi检验
     */
    @ApiOperation("保存hvi检验")
    @Log(title = "hvi检验", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveHvi")
    public AjaxResult saveHvi(@RequestBody QmsWorkorderHvi qmsWorkorderHvi) {
        Long count = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, qmsWorkorderHvi.getOrderNumber())
                .isNotNull(QmsWorkorderLog::getHvi).count();
        if (count>0){
            return AjaxResult.warn("请勿重复提交");
        }
        if (qmsWorkorderHvi.getType()==1){
            Date nowDate = DateUtils.getNowDate();
            qmsWorkorderHvi.setOverTime(nowDate);
            qmsWorkorderLogService.lambdaUpdate().set(QmsWorkorderLog::getHvi,nowDate)
                    .eq(QmsWorkorderLog::getOrderNumber, qmsWorkorderHvi.getOrderNumber())
                    .update();
            nextStatus(qmsWorkorderHvi.getOrderNumber());
        }
        QmsWorkorderHvi hvi = qmsWorkorderHviService.lambdaQuery().eq(QmsWorkorderHvi::getOrderNumber, qmsWorkorderHvi.getOrderNumber()).one();
        if (hvi!=null){
            qmsWorkorderHvi.setId(hvi.getId());
        }
        return toAjax(qmsWorkorderHviService.saveQmsWorkorderHvi(qmsWorkorderHvi));
    }

    /**
     * 保存数据审核
     */
    @ApiOperation("保存数据审核")
    @Log(title = "数据审核", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveAudit")
    public AjaxResult saveAudit(@RequestBody QmsWorkorderAudit qmsWorkorderAudit) {
        Long count = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, qmsWorkorderAudit.getOrderNumber())
                .isNotNull(QmsWorkorderLog::getAudit).count();
        if (count>0){
            return AjaxResult.warn("请勿重复提交");
        }
        if (qmsWorkorderAudit.getType()==1){
            Date nowDate = DateUtils.getNowDate();
            qmsWorkorderAudit.setOverTime(nowDate);
            qmsWorkorderLogService.lambdaUpdate().set(QmsWorkorderLog::getAudit,nowDate)
                    .eq(QmsWorkorderLog::getOrderNumber,qmsWorkorderAudit.getOrderNumber())
                    .update();
            nextStatus(qmsWorkorderAudit.getOrderNumber());
        }
        QmsWorkorderAudit audit = qmsWorkorderAuditService.lambdaQuery().eq(QmsWorkorderAudit::getOrderNumber, qmsWorkorderAudit.getOrderNumber()).one();
        if (audit!=null){
            qmsWorkorderAudit.setId(audit.getId());
        }
        return toAjax(qmsWorkorderAuditService.saveQmsWorkorderAudit(qmsWorkorderAudit));
    }

    /**
     * 保存数据审核
     */
    @ApiOperation("上传")
    @Log(title = "上传", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/doUpload")
    public AjaxResult doUpload(@RequestBody QmsWorkorder workorder)
    {
        return AjaxResult.success(qmsWorkorderService.doUpload(workorder));
    }
    /**
     * 保存hvi机台
     */
    @ApiOperation("保存hvi机台")
    @Log(title = "hvi机台", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveHviRecord")
    public AjaxResult saveHviRecord(@RequestBody List<QmsWorkorderHviRecord> workorderHviRecords)
    {
        return AjaxResult.success(qmsWorkorderHviRecordService.saveHviRecord(workorderHviRecords));
    }

    /**
     * 删除hvi机台
     */
    @ApiOperation("删除hvi机台")
    @Log(title = "hvi机台", businessType = BusinessType.DELETE)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/removeHviRecord")
    public AjaxResult removeHviRecord( Long id)
    {
        return toAjax(qmsWorkorderHviRecordService.removeById(id));
    }

    /**
     * 获取编号
     */
    @ApiOperation("获取编号")
    @GetMapping("/getOrderNumber")
    public AjaxResult getOrderNumber() {
        return AjaxResult.success(qmsWorkorderService.getOrderNumber());
    }

    /**
     * 删除流转单
     */
    @ApiOperation("删除")
    @Log(title = "流转单", businessType = BusinessType.DELETE)
	@PostMapping("/delete")
    public AjaxResult delete(@RequestBody Long id) {
        return toAjax(qmsWorkorderService.deleteQmsWorkorderById(id));
    }

    @ApiOperation("保存回潮率记录")
    @PostMapping("/saveBalanceRecord")
    public AjaxResult saveBalanceRecord(@RequestBody BalanceRecordDTO dto) {
        qmsWorkorderSampleBalanceService.saveBalanceRecord(dto);
        return AjaxResult.success();
    }

    @ApiOperation("查询回潮率记录")
    @GetMapping("/getBalanceRecord")
    public AjaxResult getBalanceRecord(BalanceRecordDTO dto) {
        return AjaxResult.success(qmsWorkorderSampleBalanceService.getBalanceRecord(dto));
    }

    /**
     * 批量删除流转单
     */
    @ApiOperation("批量删除")
    @Log(title = "流转单", businessType = BusinessType.DELETE)
    @PostMapping("/deleteBatch")
    public AjaxResult deleteBatch(@RequestBody Long[] ids) {
        return toAjax(qmsWorkorderService.deleteQmsWorkorderByIds(ids));
    }





    private void nextStatus(String number){
        QmsWorkorder workorder = qmsWorkorderService.lambdaQuery().eq(QmsWorkorder::getOrderNumber, number).one();
        QmsWorkorderLog log = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, number).one();

        if (log.getAudit()!=null){
            workorder.setStatus(5);
        }else if (log.getHvi()!=null){
            workorder.setStatus(4);
        }else if (log.getBalance()!=null){
            workorder.setStatus(3);
        }else if (log.getSense()!=null){
            workorder.setStatus(2);
        }else if (log.getDelivery()!=null){
            workorder.setStatus(1);
        }
        qmsWorkorderService.updateById(workorder);
    }





    /**
     * 获取流转单详细信息
     */
    @ApiOperation("报表查看")
    @GetMapping(value = "/report-view")
    public AjaxResult reportView( Long id) {
        QmsWorkorder workorder = qmsWorkorderService.view(id);
        if (workorder==null){
            return AjaxResult.error();
        }

        JSONObject object = new JSONObject();
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy年MM月dd日");
        object.put("orderNumber",workorder.getOrderNumber());
        object.put("type",workorder.getOrderType());
        object.put("processors",workorder.getProcessors());
        object.put("bar",getUrl(workorder.getBarCode()));
        if (workorder.getStartTime()!=null){
            object.put("orderStartTime",format2.format(workorder.getStartTime()));
        }
        if (workorder.getEndTime()!=null){
            object.put("orderEndTime",format2.format(workorder.getEndTime()));
        }
        QmsWorkorderSampleDelivery delivery = workorder.getWorkorderSampleDelivery();
        if (delivery!=null){
            if (delivery.getDeliveryTime()!=null){
                object.put("deliveryTime",format.format(delivery.getDeliveryTime()));
            }
            object.put("deliverySign",getUrl(delivery.getAdministratorSign()));
            object.put("deliveryOpinion",delivery.getOpinion());
            object.put("bagSum",delivery.getBagSum());
            object.put("batchNumber",workorder.getBatchNumber());
            object.put("boxNumber",delivery.getBoxNumber());
            object.put("boxSum",delivery.getBoxSum());
            object.put("carSum",delivery.getCarSum());
            object.put("carNumber",delivery.getCarNumber());
            object.put("sampleSum",delivery.getSampleSum());
            object.put("deliveryTestAuditorSign",getUrl(delivery.getDeliveryAuditorSign()));
            object.put("deliveryTesterSign",getUrl(delivery.getDeliveryTesterSign()));

            String deliveryTesterCode = delivery.getDeliveryTesterCode();
            if (deliveryTesterCode!=null && !deliveryTesterCode.isEmpty()){
                deliveryTesterCode = getCode(deliveryTesterCode);
                object.put("deliveryTestRemark",delivery.getDeliveryRemark()==null?"":delivery.getDeliveryRemark()+"\n回潮测试仪："+deliveryTesterCode);
            }else {
                object.put("deliveryTestRemark",delivery.getDeliveryRemark()==null?"":delivery.getDeliveryRemark());
            }
            if (delivery.getDeliveryTestTime()!=null){
                object.put("deliveryTestTime",format.format(delivery.getDeliveryTestTime()));
            }
        }
        QmsWorkorderSense sense = workorder.getWorkorderSense();

        if (sense!=null){
            if (sense.getDeliveryTime()!=null){
                object.put("senseDeliveryTime",format.format(sense.getDeliveryTime()));
            }
            object.put("senseOpinion",sense.getOpinion());
            object.put("senseSenseInspectorSign",getUrl(sense.getSenseInspectorSign()));
            object.put("senseSampleAdministratorSign",getUrl(sense.getSampleAdministratorSign()));
            object.put("senseSensePrincipalSign",getUrl(sense.getSensePrincipalSign()));
        }
        QmsWorkorderSampleBalance balance = workorder.getWorkorderSampleBalance();
        if (balance!=null){
            if (balance.getDeliveryTime()!=null){
                object.put("balanceDeliveryTime",format.format(balance.getDeliveryTime()));
            }
            object.put("balanceStartTime",format.format(balance.getStartTime()));
            object.put("balanceEndTime",format.format(balance.getEndTime()));
            object.put("balanceOpinion",balance.getOpinion());
            object.put("balanceSenseInspectorSign",getUrl(balance.getSenseInspectorSign()));
            object.put("balanceSampleBalanceAdministratorSign",getUrl(balance.getSampleBalanceAdministratorSign()));
            object.put("preconditionHours",balance.getPreconditionHours());

            object.put("beforeAuditorSign",getUrl(balance.getBeforeAuditorSign()));
            object.put("beforeTesterSign",getUrl(balance.getBeforeTesterSign()));


            String beforeTesterCode = balance.getBeforeTesterCode();
            if (beforeTesterCode!=null && !beforeTesterCode.isEmpty()){
                beforeTesterCode = getCode(beforeTesterCode);
                object.put("beforeRemark",balance.getBeforeRemark()==null?"":balance.getBeforeRemark()+"\n回潮测试仪："+beforeTesterCode);
            }else {
                object.put("beforeRemark",balance.getBeforeRemark()==null?"":balance.getBeforeRemark());
            }



            if (balance.getBeforeTestTime()!=null){
                object.put("beforeTestTime",format.format(balance.getBeforeTestTime()));
            }
            if (balance.getAfterTestTime()!=null){
                object.put("afterTestTime",format.format(balance.getAfterTestTime()));
            }
            object.put("afterAuditorSign",getUrl(balance.getAfterAuditorSign()));
            object.put("afterTesterSign",getUrl(balance.getAfterTesterSign()));

            String afterTesterCode = balance.getAfterTesterCode();
            if (afterTesterCode!=null && !afterTesterCode.isEmpty()){
                afterTesterCode = getCode(afterTesterCode);
                object.put("afterRemark",balance.getAfterRemark()==null?"":balance.getAfterRemark()+"\n回潮测试仪："+afterTesterCode);
            }else {
                object.put("afterRemark",balance.getAfterRemark()==null?"":balance.getAfterRemark());
            }



        }

        QmsWorkorderHvi hvi = workorder.getWorkorderHvi();
        if (hvi!=null){
            if (hvi.getDeliveryTime()!=null){
                object.put("hviDeliveryTime",format.format(hvi.getDeliveryTime()));
            }
            object.put("hviOpinion",hvi.getOpinion());
            if (hvi.getFinishTime()!=null){
                object.put("hviFinishTime",format.format(hvi.getFinishTime()));
            }
            object.put("hviPrincipalSign",getUrl(hvi.getPrincipalSign()));
            List<QmsWorkorderHviRecord> list = qmsWorkorderHviRecordService.lambdaQuery().eq(QmsWorkorderHviRecord::getHviId, hvi.getId()).list();
            if (list!=null && !list.isEmpty()){
                for (int i = 0; i < list.size(); i++) {
                    if (i>3){
                        break;
                    }
                    QmsWorkorderHviRecord record = list.get(i);
                    object.put("record_hviMachineNumber"+(i+1),record.getHviMachineNumber());
                    object.put("record_hviOperatorSign"+(i+1),getUrl(record.getOperatorSign()));
                    object.put("record_empId"+(i+1),record.getEmployeeId());
                    object.put("record_userName"+(i+1),record.getUserName());
                    object.put("record_realSum"+(i+1),record.getRealSum());
                }
            }
        }

        QmsWorkorderAudit audit = workorder.getWorkorderAudit();

        if (audit!=null){
            object.put("auditOpinion",audit.getOpinion());
            if (audit.getOverTime()!=null){
                object.put("auditOverTime",format.format(audit.getOverTime()));
            }
            if (workorder.getUploadTime()!=null){
                object.put("uploadTime",format.format(workorder.getUploadTime()));
            }
            object.put("auditPrincipalSign",getUrl(audit.getPrincipalSign()));
            object.put("auditSysAdminSign",getUrl(audit.getSysAdminSign()));
        }
        return AjaxResult.success(object);
    }

    private String getUrl(String img){
        if (img !=null && !img.isEmpty()){
            String sql = "select config_value from sys_config where config_key = 'path'" ;
            String path = SqlRunner.db().selectObj(sql).toString();

            try {
                if (img.startsWith("/")){
                    return path + img;
                }
                img = img.substring(1, img.length() - 1);
                JSONObject object = JSONObject.parseObject(img);
                return path + object.getString("fileName");

        }catch (Exception e){
            e.printStackTrace();
        }
        }
        return null;
    }
    private String getCode(String deliveryTesterCode){
        String[] codes = deliveryTesterCode.split(";");
        for (int i = 0; i < codes.length; i++) {
            String code = codes[i];
            if (code!=null && !code.isEmpty()){
                String[] split = code.split(",");
                if (split.length>0){
                    split[0] = "编号:"+split[0];
                }
                if (split.length>1){
                    split[1] = "型号:"+split[1];
                }
                code = String.join(",", split);
            }
            codes[i] = code;
        }
        deliveryTesterCode = String.join(";", codes);
        return deliveryTesterCode;
    }

    @ApiOperation("报表查看b")
    @GetMapping(value = "/report-view-b")
    public AjaxResult reportViewB( Long id) {
        JSONObject res = new JSONObject();
        QmsWorkorder workorder = qmsWorkorderService.view(id);
        if (workorder == null) {
            return AjaxResult.error();
        }
        QmsWorkorderSampleBalance balance = workorder.getWorkorderSampleBalance();
        QmsWorkorderSampleDelivery delivery = workorder.getWorkorderSampleDelivery();
        if (balance!=null){
            List<QmsWorkorderSampleBalanceRecord> deliveryRecords = JSONArray.parseArray(delivery.getDeliveryTestRecord(), QmsWorkorderSampleBalanceRecord.class);
            if (deliveryRecords!=null && !deliveryRecords.isEmpty()){
//                deliveryRecords = deliveryRecords.stream().sorted(Comparator.comparing(QmsWorkorderSampleBalanceRecord::getPackageNumber)).collect(Collectors.toList());
                for (int i = 0; i < deliveryRecords.size(); i++) {
                    if (i>20){
                        break;
                    }
                    QmsWorkorderSampleBalanceRecord record = deliveryRecords.get(i);
                    if (record.getPackageNumber()!=null){
                        res.put("delivery_packageNumber"+(i+1),record.getPackageNumber());
                        res.put("delivery_moistureRegain"+(i+1),record.getMoistureRegain());
                    }
                }
            }
            List<QmsWorkorderSampleBalanceRecord> beforeRecords = JSONArray.parseArray(balance.getBeforeTestRecord(), QmsWorkorderSampleBalanceRecord.class);
            if (beforeRecords!=null && !beforeRecords.isEmpty()){
//                beforeRecords = beforeRecords.stream().sorted(Comparator.comparing(QmsWorkorderSampleBalanceRecord::getPackageNumber)).collect(Collectors.toList());
                for (int i = 0; i < beforeRecords.size(); i++) {
                    if (i>20){
                        break;
                    }
                    QmsWorkorderSampleBalanceRecord record = beforeRecords.get(i);
                    if (record.getPackageNumber()!=null){
                        res.put("before_packageNumber"+(i+1),record.getPackageNumber());
                        res.put("before_moistureRegain"+(i+1),record.getMoistureRegain());
                    }
                }
            }
            List<QmsWorkorderSampleBalanceRecord> afterRecords = JSONArray.parseArray(balance.getAfterTestRecord(), QmsWorkorderSampleBalanceRecord.class);
            if (afterRecords!=null && !afterRecords.isEmpty()){
//                afterRecords = afterRecords.stream().sorted(Comparator.comparing(QmsWorkorderSampleBalanceRecord::getPackageNumber)).collect(Collectors.toList());
                for (int i = 0; i < afterRecords.size(); i++) {
                    if (i>20){
                        break;
                    }
                    QmsWorkorderSampleBalanceRecord record = afterRecords.get(i);
                    if (record.getPackageNumber()!=null){
                        res.put("after_packageNumber"+(i+1),record.getPackageNumber());
                        res.put("after_moistureRegain"+(i+1),record.getMoistureRegain());
                   }
                }
            }
        }
        return AjaxResult.success(res);
    }

    @ApiOperation(value = "读取条码")
    @PostMapping("/readBarcode")
    public AjaxResult readBarcode(MultipartFile file){


        if (file.isEmpty()) {
            return AjaxResult.success("上传文件为空");
        }

            // 读取图片
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException("条形码无法读取");
        }

        new BufferedImageLuminanceSource(bufferedImage);
            // 将图片转换为BinaryBitmap
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));

            // 设置解码提示
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

            // 创建MultiFormatReader进行识别
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            Result result = null;
            try {
                result = multiFormatReader.decode(binaryBitmap, hints);
            } catch (NotFoundException e) {
                throw new RuntimeException("无法识别条形码");
            }
        String resultText = result.getText();
            String sql = "select digits from qms_barcode_config where enable = 1" ;
            Integer digits = (Integer) SqlRunner.db().selectObj(sql);
            if (digits!=null){

                resultText = resultText.substring(resultText.length() - digits);
            }

            return AjaxResult.success((Object)resultText);

    }
    /**
     * 导出流转单列表
     */
    @ApiOperation("导出")
    @Log(title = "流转单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QmsWorkorder qmsWorkorder) {
        List<QmsWorkorder> list = qmsWorkorderService.selectQmsWorkorderList(qmsWorkorder);
        list.forEach(workorder -> {
            workorder.setStatusName(DictUtils.getDictLabel(
                    "order_status",workorder.getStatus().toString(),  ""));
            workorder.setOrderTypeName(DictUtils.getDictLabel(
                    "order_type",workorder.getOrderType().toString(),  ""));

        });
        ExcelUtil<QmsWorkorder> util = new ExcelUtil<QmsWorkorder>(QmsWorkorder.class);
        util.exportExcel(response, list, "流转单数据");
    }

    /**
     * 导入流转单列表
     */
    @ApiOperation("导入")
    @Log(title = "流转单", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<QmsWorkorder> util = new ExcelUtil<QmsWorkorder>(QmsWorkorder.class);
        List<QmsWorkorder> qmsWorkorderList = util.importExcel(file.getInputStream());
        if (StringUtils.isNull(qmsWorkorderList) || qmsWorkorderList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (QmsWorkorder qmsWorkorder : qmsWorkorderList){
            try {
                boolean res = qmsWorkorderService.saveQmsWorkorder(qmsWorkorder);
                if (res){
                    successNum++;
                }
            }
            catch (Exception e) {
                failureNum++;
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确");
            throw new ServiceException(failureMsg.toString());
        }
        else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return success(successMsg);
    }

    @ApiOperation("导出流转卡")
    @GetMapping("/findWorkOrderDetail")
    public void findWorkOrderDetail(Long id,HttpServletResponse response){
        QmsWorkorder workorder = qmsWorkorderService.getById(id);
        response.setContentType("application/pdf");
        File pdfFile = null;

        pdfFile=qmsWorkorderService.findWorkOrderDetail(workorder,getUrl(workorder.getBarCode()));
        if (pdfFile.exists()) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(pdfFile);

                OutputStream out = response.getOutputStream();
                byte[] b = new byte[1024 * 5];
                int n;
                while ((n = in.read(b)) != -1) {
                    out.write(b, 0, n);
                }
                out.flush();
                in.close();
                out.close();
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
